from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import CommunityPost
from elasticsearch import Elasticsearch
import datetime

es = Elasticsearch(['http://localhost:9200'])

HOT_FIELDS = [
    "id", "title", "content", "duration", "pace", "calorie",
    "created_at", "user_username", "user_level", "user_avatar"
]

def model_to_hot_cold_dict(instance):
    hot = {}
    cold = {}
    # post字段
    for field in instance._meta.fields:
        value = getattr(instance, field.name)
        # 处理datetime
        if isinstance(value, datetime.datetime):
            value = value.strftime('%Y-%m-%dT%H:%M:%S')
        # 处理model对象
        elif hasattr(value, 'id'):
            value = value.id
        cold[field.name] = value
    # user字段
    if hasattr(instance, 'user'):
        user = instance.user
        for field in user._meta.fields:
            v = getattr(user, field.name)
            if isinstance(v, datetime.datetime):
                v = v.strftime('%Y-%m-%dT%H:%M:%S')
            cold[f"user_{field.name}"] = v
    # 热字段（只挑选）
    for k in HOT_FIELDS:
        if k in cold:
            hot[k] = cold[k]
    return hot, cold

@receiver(post_save, sender=CommunityPost)
def community_post_created(sender, instance, created, **kwargs):
    hot_doc, cold_doc = model_to_hot_cold_dict(instance)
    user = instance.user if hasattr(instance, 'user') else None
    # 兼容无username字段
    user_display = getattr(user, 'nickname', None) or getattr(user, 'phone', '') or ''
    hot_doc['user_id'] = user.id if user else None
    hot_doc['user_phone'] = getattr(user, 'phone', '') if user else ''
    hot_doc['user_created_at'] = user.created_at.strftime('%Y-%m-%dT%H:%M:%S') if user and user.created_at else ''
    es.index(index="community_posts_hot", id=instance.id, body=hot_doc)
    es.index(index="community_posts_cold", id=instance.id, body=cold_doc)
    if created:
        print(f"新社区动态发布并同步ES（热/冷分流）：{instance.title} by {user_display}")
    else:
        print(f"社区动态更新并同步ES（热/冷分流）：{instance.title} by {user_display}")
    # 这里可以扩展：推送消息、写日志、发通知等 